using Avalonia.Controls;
using Avalonia.Interactivity; // Required for OnLoaded
using Avalonia.Threading; // Required for Dispatcher
using SerialTool.Services;
using SerialTool.ViewModels; // Required for MainWindowViewModel
using System; // 添加 System 命名空间引用
using System.Collections.Specialized; // Required for INotifyCollectionChanged
using System.Linq; // Required for LastOrDefault

namespace SerialTool.Views;

public partial class MainWindow : Window
{
    private ListBox? _communicationListBox;
    private MainWindowViewModel? _viewModel;
    private Panel? _toastContainer;

    public MainWindow()
    {
        InitializeComponent();
        // 获取 ListBox 控件的引用，确保在 InitializeComponent 之后
        _communicationListBox = this.FindControl<ListBox>("CommunicationListBox");
        _toastContainer = this.FindControl<Panel>("ToastContainer");

        this.DataContextChanged += MainWindow_DataContextChanged;
        // 如果 DataContext 已经设置，立即处理
        if (this.DataContext is MainWindowViewModel vm)
        {
            SubscribeToViewModel(vm);
        }

        // 添加窗口事件处理
        this.Closing += MainWindow_Closing;
        this.Opened += MainWindow_Opened;
        this.Loaded += MainWindow_Loaded;
    }

    private void MainWindow_Loaded(object? sender, RoutedEventArgs e)
    {
        // 初始化Toast服务
        if (_toastContainer != null)
        {
            ToastService.Instance.Initialize(_toastContainer);
        }
    }

    private void MainWindow_Opened(object? sender, EventArgs e)
    {
        if (_viewModel != null)
        {
            // 恢复窗口状态
            if (_viewModel.GetWindowWidth() > 0 && _viewModel.GetWindowHeight() > 0)
            {
                this.Width = _viewModel.GetWindowWidth();
                this.Height = _viewModel.GetWindowHeight();
            }

            // 恢复窗口最大化状态
            if (_viewModel.GetIsWindowMaximized())
            {
                this.WindowState = WindowState.Maximized;
            }
        }
    }

    private void MainWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
    {
        if (_viewModel != null)
        {
            // 窗口关闭时保存尺寸（如果不是最大化状态）
            if (this.WindowState != WindowState.Maximized)
            {
                _viewModel.SetWindowSize((int)this.Width, (int)this.Height);
            }

            // 保存窗口是否最大化
            _viewModel.SetIsWindowMaximized(this.WindowState == WindowState.Maximized);
        
            // 保存设置
            _viewModel.SaveSettingsOnExit();
        }
    }

    private void MainWindow_DataContextChanged(object? sender, System.EventArgs e)
    {
        if (_viewModel != null)
        {
            _viewModel.FilteredMessages.CollectionChanged -= ViewModel_FilteredMessages_CollectionChanged;
        }

        if (this.DataContext is MainWindowViewModel newViewModel)
        {
            SubscribeToViewModel(newViewModel);
        }
        else
        {
            _viewModel = null;
        }
    }

    private void SubscribeToViewModel(MainWindowViewModel viewModel)
    {
        _viewModel = viewModel;
        _viewModel.FilteredMessages.CollectionChanged += ViewModel_FilteredMessages_CollectionChanged;
    }

    private void ViewModel_FilteredMessages_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
    {
        // 只在添加新项且启用了自动滚动时滚动
        if (e.Action == NotifyCollectionChangedAction.Add && _communicationListBox != null && _viewModel != null && _viewModel.AutoScrollEnabled)
        {
            // 使用 Dispatcher 确保在 UI 线程执行
            Dispatcher.UIThread.InvokeAsync(() =>
            {
                // 检查滚动条是否已在底部（或接近底部），或者始终滚动
                // 这里我们简化为始终滚动
                var lastItem = _viewModel.FilteredMessages.LastOrDefault();
                if (lastItem != null)
                {
                    _communicationListBox.ScrollIntoView(lastItem);
                }
            });
        }
    }
}